import { Datum, Pie, PieConfig } from '@ant-design/charts';
import { useEffect, useState } from 'react';
import fetchDevStatisticsData from '../mockData/devStatisticsData';
import { Card, Select, theme } from 'antd';
type DataType = {
  type: string;
  value: number;
};

const DevStatistics: React.FC = () => {
  const { useToken } = theme;
  const { token } = useToken();
  const [data, setData] = useState<DataType[]>([]);
  const [devStatisticalType, setDevStatisticalType] = useState<string>('deviceType');
  useEffect(() => {
    const data = fetchDevStatisticsData(devStatisticalType);
    setData(data);
  }, [devStatisticalType]);

  const config: PieConfig = {
    appendPadding: 16,
    data,
    angleField: 'value',
    colorField: 'type',
    radius: 1,
    innerRadius: 0.64,
    meta: {
      value: {
        formatter: (v) => `${v}`,
      },
    },
    label: {
      type: 'inner',
      offset: '-50%',
      style: {
        textAlign: 'center',
      },
      autoRotate: false,
      content: '{value}',
    },
    statistic: {
      title: {
        content: '合计',
        style: {
          fontSize: `${token.fontSizeLG}px`,
        },
      },
      content: {
        content: `${data.reduce((r, d) => r + d.value, 0)}台`,
        style: {
          marginTop: '5px',
          fontSize: `${token.fontSizeXL}px`,
        },
      },
    },
    tooltip: {
      formatter: (datum: Datum) => {
        return { name: datum.type, value: datum.value + '台' };
      },
    },
    legend:
      devStatisticalType === 'machineType'
        ? {
            layout: 'horizontal',
            position: 'bottom',
            flipPage: false,
            itemSpacing: 0,
          }
        : {
            layout: 'vertical',
            position: 'right',
          },
    interactions: [{ type: 'legend-filter', enable: false }],
  };
  return (
    <Card
      title="设备统计"
      bordered={false}
      size="small"
      extra={
        <Select
          defaultValue="deviceType"
          bordered={false}
          options={[
            { label: '按类型', value: 'deviceType' },
            { label: '按厂商', value: 'manufacturerType' },
            { label: '按安装', value: 'installType' },
            { label: '按机型', value: 'machineType' },
          ]}
          onChange={(value) => {
            setDevStatisticalType(value);
          }}
        />
      }
    >
      <Pie {...config} />
    </Card>
  );
};
export default DevStatistics;
